<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        center
        show-icon
      >
      </el-alert>
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        ref="addGoodsFormRef"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0"
            >基本信息
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                prop="goods_cat"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染参数列表 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyTableData"
              :key="index"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="itemv"
                  v-for="(itemv, indexv) in item.attr_vals"
                  :key="indexv"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染静态属性列表 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyTableData"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodsForm.goods_introduce">
            </quill-editor>
            <el-button type="primary" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="picDialogVisible">
      <img :src="previewPath" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash"
export default {
    data() {
        return {
            activeIndex:'0',
            addGoodsForm:{
                goods_name:'',
                goods_price:0,
                goods_weight:0,
                goods_number:0,
                goods_cat:[],
                // 图片数组
                pics:[],
                goods_introduce:'',
                attrs:[]
               
            },
            addGoodsFormRules:{
                goods_name:[
                    {required: true, message:'请输入商品名称', trigger: 'blur'}
                ],
                goods_price:[
                    {required: true, message:'请输入价格', trigger: 'blur'}
                    ,{ type: 'number', message: '价格必须为数字值'}
                ],
                goods_number:[
                    {required: true, message:'请输入数量', trigger: 'blur'},
                    { type: 'number', message: '数量必须为数字值'}

                ],
                goods_weight:[
                    {required: true, message:'请输入重量', trigger: 'blur'},
                    { type: 'number', message: '重量必须为数字值'}

                ],
                goods_cat:[
                    {required: true, message:'请选择分类', trigger: 'blur'}
                ]

            },
            cateList:[],
            cateProps:{
                label:'cat_name',
                value:'cat_id',
                children:'children'
            },
            manyTableData:[],
            onlyTableData:[],
            uploadURL:'http://127.0.0.1:8888/api/private/v1/upload',
            headerObj:{
                Authorization:window.sessionStorage.getItem('token')
            },
            picDialogVisible:false,
            previewPath:''     
        }
    },
    created() {
        this.getCateList()
    },
    computed:{
        cateId(){
                
            if(this.addGoodsForm.goods_cat.length===3){
                return this.addGoodsForm.goods_cat[2]
            }
            return null
        }

    },
    methods: {
        async getCateList(){
           const {data:res} = await this.$http.get('categories')
           this.cateList = res.data
        },
        handleChange(){
            if(this.addGoodsForm.goods_cat.length!==3){
                this.addGoodsForm.goods_cat=[]
            }
        },
        beforeTabLeave(actName,oldActName){
            if(oldActName==='0' && (this.addGoodsForm.goods_name===''
                || this.addGoodsForm.goods_cat.length===0)  
            ){
                this.$message.error('请填完本页面再切换')
                return false
            }

        },
        async tabClicked(){
            if(this.activeIndex==='1'){
            const {data:res} = await this.$http.get('categories/'+this.cateId+'/attributes',{
                params:{'sel':'many'}
            })
            if(res.meta.status!==200){
               return this.$message.error('获取动态参数列表失败')
            }
            res.data.forEach(item => {
               item.attr_vals= item.attr_vals.length===0 ? []:item.attr_vals.split(',')
            })
            this.manyTableData = res.data

            }else if(this.activeIndex==='2'){
                const {data:res} = await this.$http.get('categories/'+this.cateId+'/attributes',{
                params:{'sel':'only'}
            })
            if(res.meta.status!==200){
               return this.$message.error('获取静态属性列表失败')
            }
            // res.data.forEach(item => {
            //    item.attr_vals= item.attr_vals.length===0 ? []:item.attr_vals.split(',')
            // })
            this.onlyTableData = res.data
        
            }
        },
        handleRemove(file){
            const filePath = file.response.data.tmp_path
            const fileIindex = this.addGoodsForm.pics.findIndex(x=>
            x.pic === filePath
            )
            this.addGoodsForm.pics.splice(fileIindex,1)
            console.log(this.addGoodsForm)
        },
        handlePreview(file){
            this.previewPath = file.response.data.url         
            this.picDialogVisible= true
        },
        // 监听图片上传成功的事件
        handleSuccess(response){
            this.addGoodsForm.pics.push({pic:response.data.tmp_path})
        },

       async addGoods(){
            this.$refs.addGoodsFormRef.validate(
                valid => {
                    if(!valid){
                        return this.$message.error('请填写必要的信息')
                    }
                }
            )
            const form = _.cloneDeep(this.addGoodsForm)
            form.goods_cat = form.goods_cat.join(',')
            this.manyTableData.forEach(item=>{
                const newInfo={
                    attr_id:item.attr_id,
                    attr_value:item.attr_vals.join(',')
                }
                this.addGoodsForm.attrs.push(newInfo)
            })
             this.onlyTableData.forEach(item=>{
                const newInfo={
                    attr_id:item.attr_id,
                    attr_value:item.attr_vals
                }
                 this.addGoodsForm.attrs.push(newInfo)

            })
            form.attrs = this.addGoodsForm.attrs 
            const{data:res} = await this.$http.post('goods',form)
            console.log(res)
            if(res.meta.status!==201){
                return this.$message.error('添加商品失败')
            }
            this.$message.success('添加商品成功')
            this.$router.push('/goods')
        }
        
    },



}
</script>

<style scoped>
.el-steps {
  margin-top: 20px;
  margin-left: 20px;
  font-size: 13px;
}
.el-step__title {
  font-size: 13px;
}
.el-dialog img {
  width: 100%;
  height: 100%;
}
.el-button {
  margin-top: 20px;
}
</style>